<template>
  <div> <LoginFormTitle class="enter-x" /> </div>
  <n-form
    ref="loginFormRef"
    :model="loginForm"
    :rules="rules"
    size="large"
    label-placement="left"
    class="p-4 enter-x w-100"
  >
    <n-form-item path="username" class="enter-x">
      <n-input v-model:value="loginForm.username" placeholder="账号" @keyup.enter="handleLogin" />
    </n-form-item>
    <n-form-item path="password" class="enter-x">
      <n-input
        type="password"
        v-model:value="loginForm.password"
        placeholder="密码"
        show-password-on="click"
        @keyup.enter="handleLogin"
      />
    </n-form-item>

    <n-form-item path="code" class="enter-x">
      <n-input
        v-model:value="loginForm.code"
        placeholder="验证码"
        @keyup.enter="handleLogin"
        style="width: 63%"
      />
      <img :src="codeUrl" @click="getCode" class="w-33% h-10 absolute right-0 cursor-pointer" />
    </n-form-item>

    <!-- <n-form-item class="enter-x">
      <n-checkbox v-model:checked="loginForm.rememberMe" size="small" style="margin-right: 12px">
        记住我
      </n-checkbox>
      <n-button class="absolute right-0" color="#18a058" text tag="a" size="small">
        忘记密码?
      </n-button>
    </n-form-item> -->
    <n-grid :cols="2" class="enter-x">
      <n-gi>
        <n-checkbox v-model:checked="loginForm.rememberMe" size="small" style="margin-right: 12px">
          记住我
        </n-checkbox>
      </n-gi>
      <n-gi>
        <n-flex justify="end" class="w-full">
          <n-button color="#18a058" text tag="a" size="small"> 忘记密码? </n-button>
        </n-flex>
      </n-gi>
    </n-grid>

    <n-form-item class="enter-x">
      <n-button class="w-full" type="primary" @click="handleLogin">登录 </n-button>
    </n-form-item>

    <n-grid x-gap="16" :cols="3" class="enter-x">
      <n-gi>
        <n-button class="w-full">手机登录 </n-button>
      </n-gi>
      <n-gi>
        <n-button class="w-full">二维码登录 </n-button>
      </n-gi>
      <n-gi>
        <n-button class="w-full">注册 </n-button>
      </n-gi>
    </n-grid>

    <n-divider> 其他登录方式 </n-divider>

    <div class="flex justify-evenly enter-x" :class="`${prefixCls}-sign-in-way`">
      <n-icon size="25" color="#888888" :component="LogoGithub" />
      <n-icon size="25" color="#888888" :component="LogoWechat" />
      <n-icon size="25" color="#888888" :component="LogoAlipay" />
      <n-icon size="25" color="#888888" :component="LogoGoogle" />
      <n-icon size="25" color="#888888" :component="LogoTwitter" />
    </div>
  </n-form>
</template>

<script name="Login" setup lang="ts">
  import { ref, reactive, watch } from 'vue';
  import Cookies from 'js-cookie';
  import { LogoGithub, LogoWechat, LogoAlipay, LogoGoogle, LogoTwitter } from '@vicons/ionicons5';
  import type { FormInst } from 'naive-ui';
  import useUserStore from '@/store/modules/user';
  import { useRouter, useRoute } from 'vue-router';

  import LoginFormTitle from './login-form-title.vue';

  import { encrypt, decrypt } from '@/utils/jsencrypt';
  import { useDesign } from '@/hooks/web/useDesign';
  import { getCodeImg } from '@/api/login';

  const { prefixCls } = useDesign('login');

  const loginFormRef = ref<FormInst | null>(null);

  const loginForm = ref({
    username: '',
    password: '',
    rememberMe: false,
    code: '',
    uuid: '',
  });
  const rules = reactive({
    username: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入账号',
    },
    password: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入密码',
    },
    code: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入验证码',
    },
  });
  let codeUrl = ref<string>('');
  const redirect = ref<any>(undefined);

  const userStore = useUserStore();
  const route = useRoute();
  const router = useRouter();

  watch(
    route,
    (newRoute) => {
      redirect.value = newRoute.query && newRoute.query.redirect;
    },
    { immediate: true },
  );

  const handleLogin = () => {
    loginFormRef.value?.validate((errors) => {
      if (!errors) {
        // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
        if (loginForm.value.rememberMe) {
          Cookies.set('username', loginForm.value.username, { expires: 30 });
          Cookies.set('password', encrypt(loginForm.value.password).toString(), { expires: 30 });
          Cookies.set('rememberMe', loginForm.value.rememberMe.toString(), { expires: 30 });
        } else {
          // 否则移除
          Cookies.remove('username');
          Cookies.remove('password');
          Cookies.remove('rememberMe');
        }
        // 调用action的登录方法
        userStore.login(loginForm.value).then(() => {
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc: any, cur) => {
            if (cur !== 'redirect') {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});

          router.push({ path: redirect.value || '/', query: otherQueryParams }).catch(() => {});
        });
        console.log('验证成功', errors);
      } else {
        console.log('验证失败');
      }
    });
    // setToken('test');
    // router.push('/index');
  };
  function getCookie() {
    const username = Cookies.get('username');
    const password = Cookies.get('password');
    const rememberMe = Cookies.get('rememberMe');
    loginForm.value.username = username === undefined ? loginForm.value.username : username;
    loginForm.value.password =
      password === undefined ? loginForm.value.password : (decrypt(password) as string);
    loginForm.value.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe);
  }
  // 获取二维码
  function getCode() {
    getCodeImg().then((res: any) => {
      codeUrl.value = 'data:image/svg+xml;base64,' + res.img;
      loginForm.value.uuid = res.uuid;
    });
  }
  getCode();
  getCookie();
</script>
